<template>
    <view :style="themeColor()">
        <scroll-view :scroll-y="true" class="w-screen h-screen bg-[var(--page-bg-color)]"
            v-if="!pageLoading && config.is_open == 1">
            <view class="sidebar-margin pt-[var(--top-m)]">
                <view class=" card-template">
                    <view class="font-500 text-[30rpx] text-[#333] leading-[42rpx] mb-[30rpx]">到账方式</view>
                    <!-- 提现到钱包余额 -->
                    <view
                        class="p-[20rpx] mb-[20rpx] flex items-center rounded-[var(--rounded-mid)] border-[1rpx] border-solid border-[#eee]"
                        v-if="config.transfer_type.includes(1)" @click="applyData.transfer_type = 1"
                        :class="{ 'border-[#00C800] bg-[#ECF9EF]': applyData.transfer_type == 1 }">
                        <view>
                            <image class="h-[60rpx] w-[60rpx]"
                                :src="img('static/resource/images/member/apply_withdrawal/bankicon.png')"
                                mode="widthFix" />
                        </view>
                        <view class="flex-1 px-[20rpx]">
                            <view class="text-[28rpx] text-[#333] leading-[40rpx] mb-[6rpx]">提现至钱包
                            </view>
                            <view class="text-[var(--text-color-light9)] text-[24rpx] leading-[34rpx]">提现至钱包余额</view>
                        </view>
                    </view>
                    <!-- 提现到微信 -->
                    <view
                        class="p-[20rpx] mb-[20rpx] flex items-center rounded-[var(--rounded-mid)] border-[1rpx] border-solid border-[#eee]"
                        v-if="config.transfer_type.includes(5)" @click="applyData.transfer_type = 5"
                        :class="{ 'border-[#00C800] bg-[#ECF9EF]': applyData.transfer_type == 5 }">
                        <view>
                            <image class="h-[60rpx] w-[60rpx]"
                                :src="img('static/resource/images/member/apply_withdrawal/wechat.png')"
                                mode="widthFix" />
                        </view>
                        <view class="flex-1 px-[20rpx]">
                            <view class="text-[28rpx] text-[#333] leading-[40rpx] mb-[6rpx]">提现至微信零钱
                            </view>
                            <view class="text-[var(--text-color-light9)] text-[24rpx] leading-[34rpx]">提现到微信零钱</view>
                        </view>
                    </view>
                    <!-- 提现到微信 -->
                    <view
                        class="p-[20rpx] mb-[20rpx] flex items-center rounded-[var(--rounded-mid)] border-[1rpx] border-solid border-[#eee]"
                        v-if="config.transfer_type.includes(3)" @click="applyData.transfer_type = 3"
                        :class="{ 'border-[#00C800] bg-[#ECF9EF]': applyData.transfer_type == 3 }">
                        <view>
                            <image class="h-[60rpx] w-[60rpx]"
                                :src="img('static/resource/images/member/apply_withdrawal/wechat.png')"
                                mode="widthFix" />
                        </view>
                        <view class="flex-1 px-[20rpx]">
                            <view class="text-[28rpx] text-[#333] leading-[40rpx] mb-[6rpx]">提现至微信
                            </view>
                            <view class="text-[var(--text-color-light9)] text-[24rpx] leading-[34rpx]">提现到微信账号</view>
                        </view>
                    </view>

                    <!-- 提现到支付宝 -->
                    <view
                        class="p-[20rpx] mb-[20rpx] flex items-center rounded-[var(--rounded-mid)] border-[1rpx] border-solid border-[#eee]"
                        v-if="config.transfer_type.includes(4)"
                        :class="{ 'border-[#009FE8] bg-[#EEF8FC]': applyData.transfer_type == 4 }">
                        <view @click="transferAlipay">
                            <image class="h-[60rpx] w-[60rpx] align-middle"
                                :src="img('static/resource/images/member/apply_withdrawal/alipay-icon.png')"
                                mode="widthFix" />
                        </view>
                        <view class="flex-1 px-[22rpx]" @click="transferAlipay">
                            <view class="text-[28rpx] text-[#333] leading-[40rpx] mb-[6rpx]"> 提现至支付宝
                            </view>
                            <view class="text-[var(--text-color-light9)] text-[24rpx] leading-[34rpx]">
                                <!-- <view v-if="alipayAccountInfo" class="truncate max-w-[440rpx]">
                                    <text>提现到支付宝账号</text>
                                    <text class="text-[#333]">{{ alipayAccountInfo.account_no }}</text>
                                </view> -->
                                <view>提现到支付宝账号</view>
                            </view>
                        </view>

                    </view>

                    <!-- 提现到银行卡 -->
                    <view
                        class="p-[20rpx] flex items-center rounded-[var(--rounded-mid)] border-[1rpx] border-solid border-[#eee]"
                        v-if="config.transfer_type.includes(2)"
                        :class="{ 'border-[#089C98] bg-[#F6FFFF]': applyData.transfer_type == 2 }">
                        <view @click="transferBank">
                            <image class="h-[42rpx] w-[60rpx] align-middle"
                                :src="img('static/resource/images/member/apply_withdrawal/bank-icon.png')"
                                mode="widthFix" />
                        </view>
                        <view class="flex-1 px-[20rpx]" @click="transferBank">
                            <view class="text-[28rpx] text-[#333] leading-[40rpx] mb-[6rpx]">提现至银行卡
                            </view>
                            <view class="text-[var(--text-color-light9)] text-[24rpx] leading-[34rpx]">
                                <view>
                                    提现到储蓄卡
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="mt-[20rpx] mb-[20rpx] card-template">
                    <view class="font-500 text-[30rpx] text-[#333] leading-[42rpx]"> 提现金额
                    </view>
                    <view
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <text class="pt-[4rpx] text-[44rpx] text-[#333] iconfont iconrenminbiV6xx price-font "></text>
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 text-[54rpx] bg-[#fff]"
                            v-model="applyData.apply_money" maxlength="7"
                            :placeholder="applyData.apply_money ? '' : ('最小提现金额￥' + fen2yuan(config.min))"
                            placeholder-class="apply-price" :adjust-position="false" />
                        <text @click="clearMoney" v-if="applyData.apply_money"
                            class="nc-iconfont nc-icon-cuohaoV6xx1 !text-[32rpx] text-[var(--text-color-light9)]"></text>
                    </view>
                    <view class="pt-[16rpx] flex items-center justify-between px-[4rpx]">
                        <view class="text-[24rpx] text-[var(--text-color-light6)] leading-[36rpx]">
                            <text>可提现金额额:￥{{ fen2yuan(cashOutMoney) }}</text>

                        </view>
                        <!-- <view class="text-[24rpx] text-primary leading-[36rpx]" @click="allMoney">全部提现
                        </view> -->
                    </view>
                    <view class="font-500 text-[30rpx] mt-[20rpx] text-[#333] leading-[42rpx]"
                        v-show="[2, 3, 4].includes(applyData.transfer_type)"> 提现账号
                    </view>
                    <view v-show="[2, 3, 4].includes(applyData.transfer_type)"
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">

                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 text-[54rpx] bg-[#fff]"
                            v-model="applyData.accountNo" :placeholder="'请输入提现账号'" placeholder-class="apply-price"
                            :adjust-position="false" />

                    </view>
                    <view class="font-500 text-[30rpx] mt-[20rpx] text-[#333] leading-[42rpx]"
                        v-show="[3, 4].includes(applyData.transfer_type)"> 收款码
                    </view>
                    <view v-show="[3, 4].includes(applyData.transfer_type)"
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <upload-img class="mt-[20rpx]" v-model="applyData.accountQrCodeUrl" :max-count="1" />

                    </view>
                    <view class="font-500 text-[30rpx] mt-[20rpx] text-[#333] leading-[42rpx]"
                        v-show="applyData.transfer_type == 2"> 持卡人
                    </view>
                    <view v-show="applyData.transfer_type == 2"
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 text-[54rpx] bg-[#fff]"
                            v-model="applyData.name" :placeholder="'请输入持卡人姓名'" placeholder-class="apply-price"
                            :adjust-position="false" />

                    </view>
                    <view class="font-500 text-[30rpx] mt-[20rpx] text-[#333] leading-[42rpx]"
                        v-show="applyData.transfer_type == 2"> 提现银行
                    </view>
                    <view v-show="applyData.transfer_type == 2"
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 text-[54rpx] bg-[#fff]"
                            v-model="applyData.bankName" :placeholder="'请输入提现银行'" placeholder-class="apply-price"
                            :adjust-position="false" />

                    </view>
                    <view class="font-500 text-[30rpx] mt-[20rpx] text-[#333] leading-[42rpx]"
                        v-show="applyData.transfer_type == 2"> 开户地址
                    </view>
                    <view v-show="applyData.transfer_type == 2"
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 text-[54rpx] bg-[#fff]"
                            v-model="applyData.bankAddress" :placeholder="'请输入开户地址'" placeholder-class="apply-price"
                            :adjust-position="false" />

                    </view>

                </view>




                <view class=" bottom-[0] tab-bar left-0 right-0 px-[var(--sidebar-m)]">
                    <button class="h-[80rpx] !text-[#fff] leading-[80rpx] primary-btn-bg rounded-[50rpx] text-[26rpx]"
                        :disabled="applyData.apply_money == '' || applyData.apply_money == 0" :loading="loading"
                        @click="cashOut">立即提现</button>
                    <view class="mt-[30rpx] text-center text-[26rpx] text-primary"
                        @click.stop="redirect({ url: '/addon/commission/pages/detailed_account', param: { type: '2' } })">
                        提现记录
                    </view>
                </view>
                <view class="tab-bar-placeholder"></view>


            </view>
        </scroll-view>
        <view class="h-[100vh] w-[100vw] bg-[var(--page-bg-color)] overflow-hidden"
            v-if="config.is_open == 0 && !pageLoading">
            <view class="empty-page">
                <image class="img" :src="img('addon/shop/cart-empty.png')" model="aspectFit" />
                <view class="desc">提现设置未开启</view>
            </view>
        </view>
        <loading-page :loading="pageLoading"></loading-page>
    </view>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { t } from '@/locale'
import { moneyFormat, redirect, getToken, img, deepClone } from '@/utils/common'
import uploadImg from './../components/upload-img.vue'

import useMemberStore from '@/stores/member'
import { cashOutApply } from './../api/commission'
import { getTradeConfig, getBrokerageUser } from './../api/commission'
import { onLoad } from '@dcloudio/uni-app'
import { fen2yuan } from '@/utils/formatting'

const pageLoading = ref(true)
const loading = ref(false)
const memberStore = useMemberStore()

// 申请提现数据
const applyData = reactive({
    apply_money: '',
    transfer_type: 1,
    // account_type: 'money',
    // account_id: 0,
    accountNo: undefined,
    accountQrCodeUrl: [],
    name: undefined,
    bankName: undefined,
    bankAddress: undefined,
})

// 可提现金额
const cashOutMoney = computed(() => {
    return brokerageInfo.value ? brokerageInfo.value.brokeragePrice : 0

    // return memberStore.info ? memberStore.info[applyData.account_type] : 0
})

// watch(() => applyData.transfer_type, (nval) => {
//     switch (nval) {
//         case 'bank':
//             applyData.account_id = bankAccountInfo.value ? bankAccountInfo.value.account_id : 0
//             break;
//         case 'alipay':
//             applyData.account_id = alipayAccountInfo.value ? alipayAccountInfo.value.account_id : 0
//             break;
//         default:
//             applyData.account_id = 0
//     }
// }, { immediate: true })

const config = reactive<AnyObject>({
    is_auto_transfer: 0, // 是否自动转账
    is_auto_verify: 0, // 是否自动审核
    is_open: 1, // 是否启用提现
    min: 0, // 最低提现金额
    rate: 0, // 手续费比率
    transfer_type: [] // 提现方式
})
const tradeConfig = reactive<AnyObject>({
    frozenDays: 0, // 冻结天数
    withdrawTypes: [], // 提现方式
})
const brokerageInfo = ref() //分销信息
let query: any = {}

onLoad(async (data) => {
    query = data

    // uni.getStorageSync('cashOutAccountType') && (applyData.account_type = uni.getStorageSync('cashOutAccountType'))

    if (getToken()) {
        memberStore.getMemberInfo()
    }

    // if (!['money', 'commission'].includes(applyData.account_type)) {
    //     uni.showToast({
    //         title: t('abnormalOperation'),
    //         icon: 'none',
    //         success() {
    //             setTimeout(() => {
    //                 if (getCurrentPages().length > 1) {
    //                     uni.navigateBack({
    //                         delta: 1
    //                     });
    //                 } else {
    //                     redirect({
    //                         url: '/app/pages/member/index',
    //                         mode: 'reLaunch'
    //                     });
    //                 }
    //             }, 1500)
    //         }
    //     })
    //     return
    // }

    // // 提现配置
    // await cashOutConfig().then((res: any) => {
    //     for (let key in deepClone(res.data)) {
    //         config[key] = deepClone(res.data[key]);
    //     }
    //     if (config.transfer_type.includes('wechatpay') && memberStore.info && (!memberStore.info.wx_openid && !memberStore.info.weapp_openid)) config.transfer_type.splice(config.transfer_type.indexOf('wechatpay'), 1)
    //     config.transfer_type.includes('bank') && getBankAccountInfo()
    //     config.transfer_type.includes('alipay') && getAlipayAccountInfo()
    //     applyData.transfer_type = config.transfer_type[0]
    //     if (query.type) {
    //         applyData.transfer_type = query.type
    //     }
    //     pageLoading.value = false
    // })
    //交易配置
    await getTradeConfig().then((res: any) => {
        config.min = res.data.brokerageWithdrawMinPrice || 0;
        tradeConfig.frozenDays = res.data.brokerageFrozenDays || 0;
        config.transfer_type = res.data.brokerageWithdrawTypes;
        config.transfer_type.push(5)
        pageLoading.value = false

    })

    await getBrokerageUser().then((res: any) => {
        brokerageInfo.value = res.data
    })
})

//全部提现
const allMoney = () => {
    if (parseFloat(cashOutMoney.value)) applyData.apply_money = moneyFormat(cashOutMoney.value)
}

// 清空提现金额
const clearMoney = () => {
    applyData.apply_money = '';
}

const verify = () => {
    if (!applyData.transfer_type) {
        uni.showToast({ title: '没有可用的提现方式', icon: 'none' })
        return false
    }
    if (uni.$u.test.isEmpty(applyData.apply_money)) {
        uni.showToast({ title: '请输入提现金额', icon: 'none' })
        return false
    }
    if (!uni.$u.test.amount(applyData.apply_money)) {
        uni.showToast({ title: '提现金额格式错误', icon: 'none' })
        return false
    }
    if (parseFloat(applyData.apply_money) > parseFloat(cashOutMoney.value)) {
        uni.showToast({ title: '提现金额超出可提现金额', icon: 'none' })
        return false
    }
    if (parseFloat(applyData.apply_money) < parseFloat(config.min)) {
        uni.showToast({ title: '提现金额小于最低提现金额', icon: 'none' })
        return false
    }
    return true;
}





/**
 * 申请提现
 */
const cashOut = () => {
    if (verify()) {
        if (loading.value) return
        loading.value = true
        let data = {
            price: Number(applyData.apply_money) * 100,
            type: applyData.transfer_type,
            accountNo: applyData.accountNo,
            accountQrCodeUrl: applyData.accountQrCodeUrl[0],
            name: applyData.name,
            bankName: applyData.bankName,
            bankAddress: applyData.bankAddress,
        }
        cashOutApply(data).then(res => {
            loading.value = false
            memberStore.getMemberInfo(() => { redirect({ url: '/addon/commission/pages/detailed_account', param: { type: '2' } }) })

        }).catch(() => {
            loading.value = false
        })
    }
}

// 选中提现到支付宝
const transferAlipay = () => {

    applyData.transfer_type = 4
}
// 选中提现到银行卡
const transferBank = () => {

    applyData.transfer_type = 2
}
</script>

<style lang="scss" scoped>
:deep(.apply-price) {
    color: var(--text-color-light9);
    font-size: 26rpx;
    font-weight: normal;
    line-height: 76rpx;
}

.tab-bar-placeholder {
    padding-bottom: calc(constant(safe-area-inset-bottom) + 166rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 166rpx);
}

.tab-bar {
    padding-bottom: calc(constant(safe-area-inset-bottom) + 30rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);
}
</style>
